package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.factory.MapperFactory;
import com.itheima.service.UserService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public List<User> findAll() {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);

        return dao.findAll();
    }

    @Override
    public void addUser(User user) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        dao.addUser(user);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public void updateUser(User user) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        dao.updateUser(user);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public User findById(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        return dao.findById(id);
    }

    @Override
    public void deleteById(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        dao.deleteById(id);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }
}
